<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <div>
        <p>{{ num }}</p>
        <button @click="num++">添加</button>
        <button @click="lessClick">减少</button>
      </div>
      <br />
      <br />
      <div>
        <p>{{ persons }}</p>
        <button @click="add">添加</button>
        <button @click="del">删除</button>
      </div>
    </div>

    <script src="./js/vue.js"></script>
    <script>
      const vm = new Vue({
        //存放数据
        data: {
          num: 0,
          persons: [
            { id: "nowletsgo", name: "华哥", age: 28 },
            { id: "lisa", name: "宋雨琦", age: 20, sex: "女" },
            { id: "sunny", name: "sunny姐", age: 28, sex: "女" },
            { id: 4, name: "红浪漫9号技师", age: 30, sex: "女" },
            { id: 5, name: "红浪漫10号技师", age: 30, sex: "男" },
            { id: 6, name: "红浪漫11号技师", age: 30, sex: "男" },
            { id: 7, name: "红浪漫12号技师", age: 30, sex: "男" },
            { id: 8, name: "红浪漫13号技师", age: 30, sex: "女" },
          ],
        },
        // 函数 方法
        methods: {
          //减少函数
          lessClick() {
            if (this.num === 0) {
              return;
            }
            this.num--;
          },

          //添加事件
          add() {
            //添加的数据
            this.persons.push(
              { id: "sunny", name: "sunny姐", age: 20, sex: "女" },
              {id: "show", name: "技师5", age: 35, sex: "女"}
            );
            //选中下标为1的数据让他的age加1
            // this.persons[2].age++;
          },

          del() {
            //每次点击都删除最后一个元素
            this.persons.pop();

            // 点击删除按钮可以删除所有数组里面的sex属性
            /* this.persons.forEach(function(item){
                for(let key in item){
                    if(this.key === sex){
                        return delete sex;
                    }
                }
            }) */
          },
        },

        // 监视 监视数据的变化，一旦发生变化 就会触发指定函数
        watch: {
          //监视num的状态 (第一种写法)
          // newVal代表新的值 oldVal代表旧的值 （懒惰监视: 默认是不触发的）
          /* num(newVal,oldVal){
                console.log(newVal,oldVal);
            } */

          //第二种写法
          num: {
            //handler不能写错 否则会报错
            handler(newVal, oldVal) {
              console.log(newVal, oldVal);
            },

            //代表是否立即触发监视(默认是false) 立即监视
            immediate: true,
          },

          //监视persons
          persons: {
            handler(newVal, oldVal) {
              console.log(newVal, oldVal);
            },
            //深度监视
            deep: true,
          },
        },
      });

      vm.$mount("#app");
    </script>
  </body>
</html>
